const app = getApp()
const tokenManager = require('../../utils/tokenManager')

Page({
  data: {
    // 表单数据
    formData: {
      career_goals: [],
      self_evaluation: '',
      intended_industries: [],
      intended_companies: [],
      intended_positions: [],
      expected_salary: {
        min: '',
        max: ''
      },
      expected_locations: [],
      job_status: '',
      job_status_index: -1,
      available_date: '',
      willing_to_relocate: false,
      willing_to_relocate_index: -1,
      willing_to_travel: '',
      willing_to_travel_index: -1,
      work_hours_preference: '',
      work_hours_preference_index: -1
    },
    // 选择器数据
    jobStatusOptions: ['在职', '观望中', '暂不求职'],
    jobStatusValues: ['Active', 'Passive', 'Not looking'],
    relocateOptions: ['是', '否'],
    travelOptions: ['无出差', '偶尔出差', '经常出差', '频繁出差'],
    travelValues: ['None', 'Low', 'Medium', 'High'],
    workHoursOptions: ['标准工时', '弹性工作', '远程办公'],
    workHoursValues: ['Standard', 'Flexible', 'Remote'],
    // 标签数据
    industryTags: ['互联网', '金融', '教育', '医疗', '房地产', '制造业', '零售', '文化娱乐', '物联网', '其他'],
    positionTags: ['前端开发', '后端开发', '全栈开发', '移动开发', '测试工程师', '运维工程师', '产品经理', 'UI设计师', '嵌入式工程师', '其他'],
    // 表单状态
    formStatus: {
      loading: false,
      submitEnabled: true
    }
  },

  // 格式化日期，去除冗余信息
  formatDate(dateString) {
    if (!dateString) return '';
    // 只保留年月日，去除时间部分
    if (dateString.includes('T') || dateString.includes(' ')) {
      return dateString.split('T')[0].split(' ')[0];
    }
    return dateString;
  },

  onLoad() {
    this.loadCareerPlan()
  },

  // 加载已有的职业规划数据
  async loadCareerPlan() {
    try {
      const token = tokenManager.getAccessToken();
      if (!token) {
        console.error('未登录，无法获取职业规划');
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        });
        return;
      }

      const res = await app.api.careerPlan.getCareerPlan(token);
      console.log('获取职业规划原始数据:', res);
      
      if (res.code === 200 && res.data) {
        // 处理JSON格式的数据
        const processedData = { ...res.data };
        
        // 格式化日期字段
        if (processedData.available_date) {
          processedData.available_date = this.formatDate(processedData.available_date);
        }
        
        // 确保所有数组字段都是数组类型
        const arrayFields = [
          'career_goals',
          'intended_industries',
          'intended_companies',
          'intended_positions',
          'expected_locations'
        ];
        
        arrayFields.forEach(field => {
          if (typeof processedData[field] === 'string') {
            try {
              processedData[field] = JSON.parse(processedData[field]);
            } catch (e) {
              // 如果解析失败，可能是单个值，转换为数组
              processedData[field] = processedData[field] ? [processedData[field]] : [];
            }
          } else if (!Array.isArray(processedData[field])) {
            processedData[field] = [];
          }
        });

        // 处理expected_salary
        if (typeof processedData.expected_salary === 'string') {
          try {
            processedData.expected_salary = JSON.parse(processedData.expected_salary);
          } catch (e) {
            processedData.expected_salary = { min: '', max: '' };
          }
        } else if (!processedData.expected_salary || typeof processedData.expected_salary !== 'object') {
          processedData.expected_salary = { min: '', max: '' };
        }
        
        // 找出选择器对应的索引
        let job_status_index = -1;
        if (processedData.job_status) {
          job_status_index = this.data.jobStatusValues.findIndex(item => item === processedData.job_status);
        }
        
        // 处理willing_to_relocate字段（tinyint(1)类型）
        let willing_to_relocate_index = -1;
        // 确保 willing_to_relocate 被正确解释为布尔值
        let isRelocate = false;
        if (processedData.willing_to_relocate !== undefined && processedData.willing_to_relocate !== null) {
          // 将各种格式转换为布尔值
          if (typeof processedData.willing_to_relocate === 'string') {
            isRelocate = processedData.willing_to_relocate.toLowerCase() === 'true' || 
                         processedData.willing_to_relocate === '1';
          } else {
            isRelocate = Boolean(processedData.willing_to_relocate);
          }
          processedData.willing_to_relocate = isRelocate;
          willing_to_relocate_index = isRelocate ? 0 : 1;
        }
        console.log('异地工作值:', processedData.willing_to_relocate, '索引:', willing_to_relocate_index);
        
        let willing_to_travel_index = -1;
        if (processedData.willing_to_travel) {
          willing_to_travel_index = this.data.travelValues.findIndex(item => item === processedData.willing_to_travel);
        }
        
        let work_hours_preference_index = -1;
        if (processedData.work_hours_preference) {
          work_hours_preference_index = this.data.workHoursValues.findIndex(item => item === processedData.work_hours_preference);
        }
        
        this.setData({
          formData: {
            ...this.data.formData,
            ...processedData,
            job_status_index: job_status_index !== -1 ? job_status_index : -1,
            willing_to_relocate_index: willing_to_relocate_index !== -1 ? willing_to_relocate_index : -1,
            willing_to_travel_index: willing_to_travel_index !== -1 ? willing_to_travel_index : -1,
            work_hours_preference_index: work_hours_preference_index !== -1 ? work_hours_preference_index : -1
          }
        }, () => {
          console.log('加载后的表单数据:', this.data.formData);
        });
      }
    } catch (error) {
      console.error('加载职业规划失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    }
  },

  // 表单项变化处理
  handleInput(e) {
    const { field } = e.currentTarget.dataset;
    const { value } = e.detail;
    
    if (field === 'expected_salary_min' || field === 'expected_salary_max') {
      const salaryType = field.split('_')[2];
      this.setData({
        [`formData.expected_salary.${salaryType}`]: value
      });
    } else {
      this.setData({
        [`formData.${field}`]: value
      });
    }
  },

  // 标签选择处理
  handleTagSelect(e) {
    const { field } = e.currentTarget.dataset;
    const { value } = e.detail;
    
    // 确保value是数组
    const selectedTags = Array.isArray(value) ? value : [value];
    
    this.setData({
      [`formData.${field}`]: selectedTags
    });
  },

  // 选择器变化处理
  handlePickerChange(e) {
    const { field } = e.currentTarget.dataset;
    const { value } = e.detail;
    
    if (field === 'job_status') {
      this.setData({
        ['formData.job_status']: this.data.jobStatusValues[value],
        ['formData.job_status_index']: parseInt(value)
      });
    } else if (field === 'willing_to_relocate') {
      // 明确将值转换为布尔类型(是=true, 否=false)
      const isRelocate = this.data.relocateOptions[value] === '是';
      console.log('设置异地工作:', isRelocate, '选择索引:', value);
      this.setData({
        ['formData.willing_to_relocate']: isRelocate,
        ['formData.willing_to_relocate_index']: parseInt(value)
      }, () => {
        console.log('设置后的异地工作值:', this.data.formData.willing_to_relocate);
      });
    } else if (field === 'willing_to_travel') {
      this.setData({
        ['formData.willing_to_travel']: this.data.travelValues[value],
        ['formData.willing_to_travel_index']: parseInt(value)
      });
    } else if (field === 'work_hours_preference') {
      this.setData({
        ['formData.work_hours_preference']: this.data.workHoursValues[value],
        ['formData.work_hours_preference_index']: parseInt(value)
      });
    } else if (field === 'available_date') {
      // 格式化日期，确保只保留年月日
      const formattedDate = this.formatDate(value);
      this.setData({
        ['formData.' + field]: formattedDate
      });
      console.log('设置到岗时间:', formattedDate);
    }
  },

  // 表单验证
  validateForm() {
    const { formData } = this.data;
    const requiredFields = ['job_status', 'willing_to_relocate'];
    
    for (const field of requiredFields) {
      if (!formData[field]) {
        wx.showToast({
          title: `请填写${this.getFieldName(field)}`,
          icon: 'none'
        });
        return false;
      }
    }
    return true;
  },

  // 获取字段名称
  getFieldName(field) {
    const fieldNames = {
      career_goals: '职业目标',
      self_evaluation: '自我评价',
      intended_industries: '意向行业',
      intended_companies: '意向企业',
      intended_positions: '意向岗位',
      expected_salary: '期望薪资',
      expected_locations: '期望工作地点',
      job_status: '求职状态',
      available_date: '到岗时间',
      willing_to_relocate: '是否愿意异地工作',
      willing_to_travel: '出差意愿',
      work_hours_preference: '工作时间偏好'
    };
    return fieldNames[field] || field;
  },

  // 提交表单
  async handleSubmit() {
    if (!this.validateForm()) {
      return;
    }

    this.setData({
      'formStatus.loading': true,
      'formStatus.submitEnabled': false
    });

    try {
      const token = tokenManager.getAccessToken();
      if (!token) {
        throw new Error('未登录');
      }

      // 准备提交数据
      const submitData = { ...this.data.formData };
      
      // 确保日期格式正确
      if (submitData.available_date) {
        submitData.available_date = this.formatDate(submitData.available_date);
      }
      
      // 删除辅助字段
      delete submitData.job_status_index;
      delete submitData.willing_to_relocate_index;
      delete submitData.willing_to_travel_index;
      delete submitData.work_hours_preference_index;

      // 确保异地工作字段是布尔值，适应tinyint(1)
      submitData.willing_to_relocate = Boolean(submitData.willing_to_relocate);
      
      // 确保所有数组字段都是JSON字符串
      const arrayFields = [
        'career_goals',
        'intended_industries',
        'intended_companies',
        'intended_positions',
        'expected_locations'
      ];
      
      arrayFields.forEach(field => {
        if (Array.isArray(submitData[field])) {
          submitData[field] = JSON.stringify(submitData[field]);
        }
      });

      // 确保expected_salary是JSON字符串
      if (typeof submitData.expected_salary === 'object') {
        submitData.expected_salary = JSON.stringify(submitData.expected_salary);
      }

      console.log('提交的表单数据:', submitData);
      const res = await app.api.careerPlan.updateCareerPlan(token, submitData);
      
      if (res.code === 200) {
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        });
        setTimeout(() => {
          // 跳转到个性化页面
          wx.navigateTo({
            url: '/pages/personality/personality'
          });
        }, 1500);
      } else {
        throw new Error(res.message || '保存失败');
      }
    } catch (error) {
      console.error('保存职业规划失败:', error);
      wx.showToast({
        title: error.message || '保存失败',
        icon: 'none'
      });
    } finally {
      this.setData({
        'formStatus.loading': false,
        'formStatus.submitEnabled': true
      });
    }
  }
});